import React, {
  useRef,
  forwardRef,
  useImperativeHandle,
} from "react";

import SunEditor from "suneditor-react";
import SunEditorCore from "suneditor/src/lib/core";

import "../../src/assets/product_viewer.css"; // 引入产品查看器样式
import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS File

// 环境变量配置
const UPLOAD_BASE_URL = process.env.REACT_APP_UPLOAD_BASE_URL || "http://localhost:7800";

interface AIEditorProps {
  initialData: string;
  getData: (data: string) => void;
  onSave?: () => void;
  onReset?: () => void;
}

interface AIEditorRef {
  reset: () => void;
  getCurrentData: () => string;
}

const AIEditor = forwardRef<AIEditorRef, AIEditorProps>(
  ({ initialData, getData, onSave, onReset }, ref) => {
    const editorRef = useRef<SunEditorCore>(null);

    const getCurrentData = () => {
      if (editorRef.current) {
        const data = editorRef.current.getContents(true);
        return data;
      }
      return "";
    };

    const handleReset = () => {
      if (editorRef.current) {
        editorRef.current.setContents(initialData); // 重置内容
      }
      if (onReset) {
        onReset();
      }
    };

    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
      reset: handleReset,
      getCurrentData: getCurrentData,
    }));

    return (
      <div>
        <SunEditor
          setOptions={{
            strictMode: false,
            strictHTMLValidation: false,
            imageUploadUrl: `${UPLOAD_BASE_URL}/apis/ctrip/upload/background`,
            audioUploadUrl: `${UPLOAD_BASE_URL}/apis/ctrip/upload/background`,
            videoUploadUrl: `${UPLOAD_BASE_URL}/apis/ctrip/upload/background`,
            imageMultipleFile: true,
            videoMultipleFile: true,
            audioMultipleFile: true,
            imageAlignShow: true,
            videoAlignShow: true,
          }}
          defaultValue={initialData}
          getSunEditorInstance={(instance: SunEditorCore) => {
            editorRef.current = instance;
          }}
        />
      </div>
    );
  },
);

export default AIEditor;
